<?php
/**
 * Smarty plugin
 * @package Smarty
 * @subpackage plugins
 */


/**
 * Smarty truncate modifier plugin
 *
 * Type:     modifier<br>
 * Name:     td_truncate<br>
 * Purpose:  Truncate a string to a certain length if necessary,
 *           optionally splitting in the middle of a word, and
 *           appending the $etc string.
 * @link http://smarty.php.net/manual/en/language.modifier.truncate.php
 *          truncate (Smarty online manual)
 * @param string
 * @param integer
 * @param string
 * @param boolean
 * @return string
 */
function smarty_modifier_td_truncate($s, $nCut, $sEtc='...') {
    if (strlen($s) < $nCut) {
        return $s;
    }
    $nLength = min($nCut, strlen($s));
    $sOut = '';
    for ($i = 0; $i < $nLength; $i++) {
		if (223 < ord($s[$i])) {
			$sAdd = $s[$i].$s[$i + 1].$s[$i + 2];
            $i += 2;
		}
		elseif (127 < ord($s[$i])) {
            $sAdd = $s[$i].$s[$i + 1];
            $i += 1;
        }
        else {
            $sAdd = $s[$i];
        }
        if ($nLength < strlen($sOut.$sAdd)) {
            break;
        }
        else {
            $sOut .= $sAdd;
        }
    }
    return (strlen($sOut) < strlen($s) ? $sOut.$sEtc : $sOut);
}
?>
